import React, { Component } from 'react'
import className from 'classnames/bind'
import classNames from 'classnames'
import _ from 'loadsh'
import styles from './style.module.less'

class CustomCheckbox extends Component {
  constructor(props) {
    super(props)
    const { dataSource, value, type = 'radio' } = props
    const newValue = value || (type === 'radio' ? '' : [])
    this.state = {
      dataSource,
      value: newValue,
      type
    }
  }

  componentDidUpdate(prevProps) {
    if (!_.isEqual(prevProps, this.props)) {
      this.setState({
        ...this.props
      })
    }
  }

  checkIsTarget = (v) => {
    const { type, value } = this.state
    let t = false
    if (type === 'radio') {
      t = value === v
    } else if (type === 'checkbox') {
      t = value.indexOf(v) > -1
    }
    return t
  }

  handleItem = (target) => {
    const { type, value } = this.state
    const { onChange } = this.props
    let newValue = _.cloneDeep(value)
    if (type === 'radio') {
      if (newValue === target.value) {
        newValue = ''
      } else {
        newValue = target.value
      }
    } else if (type === 'checkbox') {
      if (newValue.indexOf(target.value) > -1) {
        newValue = _.filter(newValue, (e) => e !== target.value)
      } else {
        newValue = newValue.concat(target.value)
      }
    }

    this.setState({
      value: newValue
    })

    if (onChange) {
      onChange(newValue)
    }
  }

  render() {
    const cx = className.bind(styles)
    const { dataSource, squireBorder } = this.state
    const { wrapperClassName, disabled } = this.props

    return (
      <div className={styles.checkbox}>
        <div className={styles.wrapper}>
          {!disabled
            ? dataSource.map((item) => (
                <div
                  key={item.value}
                  onClick={() => this.handleItem(item)}
                  className={className(
                    cx('itemBtn', { highlight: this.checkIsTarget(item.value) }),
                    wrapperClassName,
                    squireBorder && cx('newItem')
                  )}>
                  {item.name}
                </div>
              ))
            : dataSource.map((item) => (
                <div
                  key={item.value}
                  className={classNames(
                    cx('itemBtn', 'itemBtnDisabled', {
                      highlight: this.checkIsTarget(item.value)
                    }),
                    wrapperClassName,
                    squireBorder && cx('newItemBtn')
                  )}>
                  {item.name}
                </div>
              ))}
        </div>
      </div>
    )
  }
}

export default CustomCheckbox
